package com.yumeno.epidemic;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = "com.yumeno.epidemic.mapper")
public class MyBatisConfig {
    private static Logger logger = Logger.getLogger(MyBatisConfig.class);

    //Apache-DBCP核心类，创建一个基于连接池的数据源
    @Bean(destroyMethod = "close")     //将方法的返回对象注册到Spring的IoC容器
    public BasicDataSource basicDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/epidemic");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setInitialSize(5);
        dataSource.setMaxActive(50);
        dataSource.setMaxIdle(2);
        dataSource.setMaxWait(4000);
        dataSource.setDefaultAutoCommit(false);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sessionFactory(DataSource dataSource) {


        //用SQL会话工厂Bean来配置Sql会话工厂
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        //设置使用的数据源
        sessionFactoryBean.setDataSource(dataSource);
        SqlSessionFactory factory = null;
        try {
            //使用帮忙取得路径的辅助类将路径信息赋值给数组类型的Resources
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:com/yumeno/epidemic" +
                    "/mapper" +
                    "/*Mapper.xml");
            //使用设置好的resources，设置映射xml文件的路径
            sessionFactoryBean.setMapperLocations(resources);
            //设置xml文件中的类所在的包
            sessionFactoryBean.setTypeAliasesPackage("com.yumeno.epidemic.beans");
            //设置下划线表示法-驼峰表示法
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setMapUnderscoreToCamelCase(true);
            sessionFactoryBean.setConfiguration(configuration);
            //将配置好的sessionFactoryBean信息赋值给factory
            factory = sessionFactoryBean.getObject();
        } catch (Exception e) {
            logger.error("配置xml文件发生错误" + e.getMessage());
        }
        return factory;
    }
}
